package org.jeecg.modules.medication.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.medication.entity.MedicationShop;
import org.jeecg.modules.medication.service.IMedicationShopService;
import org.jeecg.modules.nurse_expert.entity.NurseExpert;
import org.jeecg.modules.nurse_goods.entity.NurseGoods;
import org.jeecg.modules.nurse_goods_detail.entity.NurseGoodsDetail;
import org.jeecg.modules.nurse_hospital.entity.NurseHospital;
import org.jeecg.modules.nurse_hospital.service.INurseHospitalService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 药房产品
 * @Author: jeecg-boot
 * @Date:   2025-06-14
 * @Version: V1.0
 */
@Api(tags="药房产品")
@RestController
@RequestMapping("/medication/medicationShop")
@Slf4j
public class MedicationShopController extends JeecgController<MedicationShop, IMedicationShopService>{
	@Autowired
	private IMedicationShopService medicationShopService;
	@Autowired
	private INurseHospitalService nurseHospitalService;

	/**
	 * 分页列表查询
	 *
	 * @param medicationShop
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "药房产品-分页列表查询")
	@ApiOperation(value="药房产品-分页列表查询", notes="药房产品-分页列表查询")
	@GetMapping(value = "/rootList")
	@PermissionData(pageComponent = "nurse/medication_shop/MedicationShopList")
	public Result<IPage<MedicationShop>> queryPageList(MedicationShop medicationShop,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String hasQuery = req.getParameter("hasQuery");
        if(hasQuery != null && "true".equals(hasQuery)){
            QueryWrapper<MedicationShop> queryWrapper =  QueryGenerator.initQueryWrapper(medicationShop, req.getParameterMap());
            List<MedicationShop> list = medicationShopService.queryTreeListNoPage(queryWrapper);
            IPage<MedicationShop> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        }else{
            String parentId = medicationShop.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            medicationShop.setPid(null);
            QueryWrapper<MedicationShop> queryWrapper = QueryGenerator.initQueryWrapper(medicationShop, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<MedicationShop> page = new Page<MedicationShop>(pageNo, pageSize);
            IPage<MedicationShop> pageList = medicationShopService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
	}

	 /**
	  * 【vue3专用】加载节点的子数据
	  *
	  * @param pid
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	 public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
		 Result<List<SelectTreeModel>> result = new Result<>();
		 try {
			 List<SelectTreeModel> ls = medicationShopService.queryListByPid(pid);
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 【vue3专用】加载一级节点/如果是同步 则所有数据
	  *
	  * @param async
	  * @param pcode
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		 Result<List<SelectTreeModel>> result = new Result<>();
		 try {
			 List<SelectTreeModel> ls = medicationShopService.queryListByCode(pcode);
			 if (!async) {
				 loadAllChildren(ls);
			 }
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 【vue3专用】递归求子节点 同步加载用到
	  *
	  * @param ls
	  */
	 private void loadAllChildren(List<SelectTreeModel> ls) {
		 for (SelectTreeModel tsm : ls) {
			 List<SelectTreeModel> temp = medicationShopService.queryListByPid(tsm.getKey());
			 if (temp != null && temp.size() > 0) {
				 tsm.setChildren(temp);
				 loadAllChildren(temp);
			 }
		 }
	 }

	 /**
      * 获取子数据
      * @param medicationShop
      * @param req
      * @return
      */
	//@AutoLog(value = "药房产品-获取子数据")
	@ApiOperation(value="药房产品-获取子数据", notes="药房产品-获取子数据")
	@GetMapping(value = "/childList")
	public	Result <IPage<Map<String, Object>>>queryPageList(MedicationShop medicationShop,HttpServletRequest req) {
		String org = req.getHeader("sys_org_code");
// 初始化查询包装器
		QueryWrapper<MedicationShop> queryWrapper = QueryGenerator.initQueryWrapper(medicationShop, req.getParameterMap());

// 添加机构过滤条件
		if (oConvertUtils.isNotEmpty(org)) {
			queryWrapper.eq("sys_org_code", org);
		}

// 构建价格子查询
		String priceSubQuery = "COALESCE(" +
				"(SELECT sp.price FROM standard_price sp WHERE sp.code = medication_shop.standard_code AND sp.is_default = '1' LIMIT 1), " +
				"(SELECT sp.price FROM standard_price sp WHERE sp.code = medication_shop.standard_code LIMIT 1), " +
				"0) AS stand_price";

// 重新设置查询字段，包含主表所有字段和子查询价格
		queryWrapper.select("medication_shop.*", priceSubQuery);

// 执行查询，返回Map类型结果（支持多表字段）
		List<Map<String, Object>> records = medicationShopService.listMaps(queryWrapper);
		List<Map<String, Object>> convertedRecords = new ArrayList<>();
		for (Map<String, Object> record : records) {
			convertedRecords.add(underlineToCamelCaseMap(record));
		}

// 处理分页
		IPage<Map<String, Object>> pageList = new Page<>(1, 10, convertedRecords.size());
		pageList.setRecords(convertedRecords);

		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	//@AutoLog(value = "药房产品-批量获取子数据")
    @ApiOperation(value="药房产品-批量获取子数据", notes="药房产品-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<MedicationShop> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<MedicationShop> list = medicationShopService.list(queryWrapper);
            IPage<MedicationShop> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param medicationShop
	 * @return
	 */
	@AutoLog(value = "药房产品-添加")
	@ApiOperation(value="药房产品-添加", notes="药房产品-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MedicationShop medicationShop) {
		medicationShopService.addMedicationShop(medicationShop);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param medicationShop
	 * @return
	 */
	@AutoLog(value = "药房产品-编辑")
	@ApiOperation(value="药房产品-编辑", notes="药房产品-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MedicationShop medicationShop) {
		medicationShopService.updateMedicationShop(medicationShop);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "药房产品-通过id删除")
	@ApiOperation(value="药房产品-通过id删除", notes="药房产品-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		medicationShopService.deleteMedicationShop(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "药房产品-批量删除")
	@ApiOperation(value="药房产品-批量删除", notes="药房产品-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.medicationShopService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "药房产品-通过id查询")
	@ApiOperation(value="药房产品-通过id查询", notes="药房产品-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MedicationShop> queryById(@RequestParam(name="id",required=true) String id) {
		MedicationShop medicationShop = medicationShopService.getById(id);
		if(medicationShop==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(medicationShop);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param medicationShop
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MedicationShop medicationShop) {
		return super.exportXls(request, medicationShop, MedicationShop.class, "药房产品");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, MedicationShop.class);
    }


	 /**
	  *
	  *
	  * @param pid
	  * @return
	  */
	 //@AutoLog(value = "商品管理-通过id查询")
	 @ApiOperation(value = "商品列表详情-通过pid查询", notes = "商品管理-通过id查询")
	 @GetMapping(value = "/queryListNew")
	 public Result<?> queryListNew(@RequestParam(name = "pid", required = true) String pid) {
		 List<Map<String, Object>> list = medicationShopService.queryListNew(pid);
		 return Result.OK(list);
	 }



	@AutoLog(value = "大药房-克隆商品")
	@ApiOperation(value = "大药房-克隆商品", notes = "大药房-克隆商品")
	@PostMapping(value = "/clone")
	public Result<?> cloneMedicationShop(String id, String cloneId) {
		NurseHospital sourceHospital = nurseHospitalService.getById(id);
		NurseHospital targetHospital = nurseHospitalService.getById(cloneId);
		if (sourceHospital == null || targetHospital == null) {
			return Result.error("医院信息为空");
		}
		if (sourceHospital.getId().equals(targetHospital.getId())) {
			return Result.error("不能克隆自身商品");
		}

		// 2. 查询需要克隆的所有商品（包含各级子商品）
		List<MedicationShop> allGoods = medicationShopService.list(
				new QueryWrapper<MedicationShop>().eq("sys_org_code", sourceHospital.getSysOrgCode())
		);
		if (allGoods.isEmpty()) {
			return Result.error("克隆商品为空");
		}


		// 5. 构建层级关系：父ID→子商品列表（统一父ID为"0"表示顶级，避免null键问题）
		Map<String, List<MedicationShop>> parentIdToChildren = new HashMap<>();
		for (MedicationShop goods : allGoods) {
			String parentId = (goods.getPid() == null || "0".equals(goods.getPid())) ? "0" : goods.getPid();
			parentIdToChildren.computeIfAbsent(parentId, k -> new ArrayList<>())
					.add(goods);
		}

		// 6. 初始化变量：ID映射表（原始ID→新ID）、待保存的商品和详情列表
		Map<String, String> idMapping = new HashMap<>();
		List<MedicationShop> clonedGoodsList = new ArrayList<>();

		// 7. 按层级处理商品（从顶级开始，逐层处理子商品）
		// 初始待处理的父ID为顶级标识"0"（对应原始商品中pid为null或"0"的商品）
		Queue<String> currentParentIds = new LinkedList<>();
		currentParentIds.add("0");

		while (!currentParentIds.isEmpty()) {
			String parentId = currentParentIds.poll(); // 取出当前层级的父ID（原始ID）
			List<MedicationShop> children = parentIdToChildren.getOrDefault(parentId, Collections.emptyList());

			for (MedicationShop child : children) {
				// 8. 克隆商品并生成新ID
				MedicationShop clonedGoods = new MedicationShop();
				BeanUtils.copyProperties(child, clonedGoods);
				String newGoodsId = IdWorker.getIdStr(clonedGoods); // 生成新ID

				// 设置克隆商品的属性（重置创建/更新信息，关联目标医院）
				clonedGoods.setId(newGoodsId);
				clonedGoods.setCreateBy(null);
				clonedGoods.setCreateTime(null);
				clonedGoods.setUpdateBy(null);
				clonedGoods.setUpdateTime(null);
				clonedGoods.setSysOrgCode(targetHospital.getSysOrgCode());

				// 设置父ID（如果是顶级商品，父ID保持"0"；否则从映射表取父商品的新ID）
				String newParentId = "0".equals(parentId) ? "0" : idMapping.get(parentId);
				if (newParentId == null && !"0".equals(parentId)) {
					// 校验：非顶级商品必须找到父ID映射（确保层级正确）
					return Result.error("克隆失败：商品[" + child.getId() + "]的父商品未找到");
				}
				clonedGoods.setPid(newParentId);

				// 9. 记录ID映射，添加到待保存列表
				idMapping.put(child.getId(), newGoodsId);
				clonedGoodsList.add(clonedGoods);


				// 11. 将当前商品的原始ID加入下一层级的父ID队列，准备处理其子女
				currentParentIds.add(child.getId());
			}
		}

		// 12. 批量保存所有克隆的商品和详情
		medicationShopService.saveBatch(clonedGoodsList);

		return Result.OK("多级大药房商品克隆成功！");
	}

	private String underlineToCamelCase(String underlineName) {
		if (underlineName == null || underlineName.isEmpty()) {
			return underlineName;
		}

		// 如果没有下划线，直接返回原字符串
		if (!underlineName.contains("_")) {
			return underlineName;
		}

		StringBuilder camelCase = new StringBuilder();
		boolean nextUpperCase = false;

		for (int i = 0; i < underlineName.length(); i++) {
			char c = underlineName.charAt(i);

			if (c == '_') {
				nextUpperCase = true;
			} else {
				if (nextUpperCase) {
					camelCase.append(Character.toUpperCase(c));
					nextUpperCase = false;
				} else {
					camelCase.append(c);
				}
			}
		}

		return camelCase.toString();
	}
	private Map<String, Object> underlineToCamelCaseMap(Map<String, Object> map) {
		if (map == null || map.isEmpty()) {
			return new HashMap<>();
		}

		Map<String, Object> resultMap = new HashMap<>(map.size());
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();

			// 转换下划线命名为驼峰命名
			String camelCaseKey = underlineToCamelCase(key);
			resultMap.put(camelCaseKey, value);
		}
		return resultMap;
	}

}
